<template>
  <view>
    <view class="input-search">
    	<uni-easyinput prefixIcon="search"  trim="all" v-model="keyword" :styles="styles" :placeholderStyle="placeholderStyle"></uni-easyinput>
    	<button @click="search">搜索</button>
    </view>
	<uni-table ref="table" type="selection" :loading="loading" :emptyText="emptyText" filter-type="search"  @selection-change="selectionChange">
		
		<uni-swipe-action >
			<uni-tr v-if="flag=='add'?false:true">
				<uni-th class="th-class">
					<button class="close_btn del_btn" @click="toDelete">删除</button>
					<button class="close_btn" @click="toSyn">同步</button>
					<button class="close_btn unsyn_btn" @click="toUnSyn">撤销同步</button>
					<!-- <view class="save_btn" @click="toEdit" style="margin-left: 20rpx;">编辑</view> -->
				</uni-th>
			</uni-tr>
			<uni-tr v-if="flag=='add'?true:false"> 
				<uni-th class="th-class">
					<button v-show="order_type==2?true:false" class="close_btn unsyn_btn" @click="synPdaorder(2)">下载拣货单</button>
				</uni-th>
			</uni-tr>
		<uni-swipe-action-item v-for="(item, index) in card_arr" :key="index"
							:right-options="right_options" show="none"
					    :auto-close="false"
					    @click="toDetail(item)" >
		<uni-tr >
			<uni-td align="left" class="td-class">
				<div @click="selectes(item)" @longpress="longPressDelete(index)" class="td_div">
					<!-- 上架、领料进度 -->
					<!-- <view class="td_list" v-if="order_type==0?true:false">
						<text class="label">上架：</text>
						<progress :percent="item.rat" show-info stroke-width="15" activeColor="#18bc9c" backgroundColor="#999" style="width: 82%;"></progress>
					</view> -->
					<!-- <view class="td_list" v-if="order_type==2?true:false">
						<text class="label">出库：</text>
						<progress :percent="item.rat" show-info stroke-width="15" activeColor="#18bc9c" backgroundColor="#999" style="width: 82%;"></progress>
					</view> -->
					
					<view class="td_list">
						<text class="label">单号：</text>
						<text class="text">{{ item.FBillNo }}</text>
					</view>
					<view class="td_list">
						<text class="label">源单单号：</text>
						<text class="text">{{ item.source_code }}</text>
					</view>
					<view class="td_list">
						<text class="label">日期：</text>
						<text class="text">{{ item.FDate }}</text>
					</view>
					<view class="td_list">
						<text class="label">总数：</text>
						<text class="text">{{ item.total_qty }}</text>
					</view>
					<!-- <view class="td_list">
						<text class="label">{{order_type==0?'入库数':'出库数'}}：</text>
						<text class="text">{{ item.get_qty }}</text>
					</view> -->
					
					<!-- <view class="td_list" v-show="order_type==2?true:false">
						<text class="label">暂存路径：</text>
						<text class="text">{{ item.to_shelves_name }}</text>
					</view> -->
					
					<view class="td_list">
						<!-- <text class="font-red">状态：{{ item.status==1?'有效':'关闭' }}</text> -->
						<text class="label">状态：</text>
						<text class="text font-red">{{ item.syn_status==1?'已同步':'未同步' }}</text>
					</view>
					<!-- <view>
						<text>创建日期：{{ item.create_date }}</text>
					</view> -->
					<view class="td_list">
						<text class="label">备注：</text>
						<text class="text">{{ item.a_remark }}</text>
					</view>
				</div>
			</uni-td>
        </uni-tr>
		</uni-swipe-action-item>
		</uni-swipe-action>
    </uni-table>
    <view class="uni-pagination-box">
		<uni-pagination show-icon :page-size="pageSize" :current="currentPage"
        :total="total" @change="change" />
	</view>
  </view>
</template>

<script>
// 引入uni-ui组件
import {
  uniPagination,
  uniIcons,
  uniCard,
  uniTable,
  uniTr,
  uniTh,
  uniTd,
  uniEasyinput,uniSwipeActionItem
} from "@dcloudio/uni-ui"
export default {
  data() {
    return {
      card_arr: [],//当前页码的表格数据
      pageSize: 15,// 每页数据量
      currentPage: 1,// 当前页
      total: 0,// 数据总量
      loading: false,
      selectedIndexs:[],//选中
	  
	  emptyText:'暂无更多数据',
	  placeholderStyle:'font-size:17px;',
	  styles:{
	  	borderColor: '#999'
	  },
	  keyword:'',
	  where:' 1=1 ',
	  order_type:'',
	  flag:'',
	  user:uni.getStorageSync('user'),
	  right_options: [{
			text: '明细',
			style: {
				backgroundColor: '#18bc9c'
			}
		},
	  ],
    }
  },
  components: {
    uniPagination,
    uniIcons, //uni-ui的icons组件
    uniTable,
    uniTr,
    uniTh,
    uniTd,
	uniEasyinput,uniSwipeActionItem
  },
  onPullDownRefresh() {
  	this.search()
  	uni.stopPullDownRefresh();
  },
  methods: {
	// 搜索
	search() {
		this.currentPage = 1
		this.getlist();
	},
    //获取列表
    getlist() {
		if(this.order_type == ''){
			this.$Api.msg('单据类型错误','error')
			return
		}
		
		uni.showLoading({mask:true});
		this.where = " order_type="+this.order_type+" and userid='"+this.user.userid+"' and stock_id="+this.user.stock_id
		if(this.keyword!=''){
			this.where += "  and (source_code like '%"+this.keyword+"%' or FBillNo like '%"+this.keyword+"%' or factory_name like '%"+this.keyword+"%') "
		}
		if(this.flag=='add'){
			this.where += " and status = 1"
			//取源单收货单，已同步记录，给上架做源单
			//取源单拣货单，已同步记录，给出库做源单
			if(this.order_type == 0 || this.order_type == 2){
				this.where += " and syn_status = 1"
			}
		}
		
		this.$Db.queryCount('stockbill',this.where).then(res => {
			this.total = res[0].num;//获得总页数
			if(!this.total){
				uni.hideLoading()
			}
		})
		
		if(this.flag=='add'&&!this.total){
			if(this.order_type==0){
				this.emptyText = '暂无数据,请先操作同步收货单'
			}
		}
		
		let _this = this
		this.$Db.queryDataList('stockbill',this.currentPage,this.pageSize,this.where,'id','desc').then(res => {
			//this.card_arr = res
			if(!res.length){
				this.card_arr = []
			}else{
				setTimeout(()=>{
					_this.getProgress(res)
				},500)
			}
			uni.hideLoading();
		})
    },
	getProgress(card_arr){
		if(this.flag!='add'){
			//列表，展示全部记录
			this.card_arr = card_arr;
		}else{
			this.card_arr = []
		}
		
		if(card_arr.length>0){
			card_arr.forEach((item,index)=>{
				//获取上架进度
				this.$Db.getStockbillProgress(item.FBillNo).then(res=>{
					item.rat = res.rat
					item.get_qty = res.get_qty
					item.total_qty = res.total_qty
					if(this.flag=='add'){
						//取源单，显示未上架完
						if(res.get_qty<res.total_qty){
							this.card_arr.push(item)
						}
					}else{
						this.$set(this.card_arr,index,item)
					}
				}).catch(err=>{
					console.log(err)
				}) 
			})
		}
	},
    change(e) {
      this.currentPage = e.current
      this.getlist()
    },
	// 多选
	selectionChange(e) {
		this.selectedIndexs = e.detail.index
	},
	longPressDelete(index){
		//长按 删除
		this.selectedIndexs = []
		this.selectedIndexs.push(index)
		this.toDelete()
	},
	toDelete() {
		let _this = this;
		let delFlag = true;
		if(!this.selectedIndexs.length){
			this.$Api.msg("请选择要删除的记录");
			return 
		}
		if(this.selectedIndexs.length>1){
			this.$Api.msg("请选择单条记录进行删除");
			//先这样处理，同时2条相同的记录（查询条件一致情况下，更新不生效，
			//一直返回第一次查询的结果）,怀疑是相同查询条件下，连续查询，缓存
			return 
		}
		
	  uni.showModal({
	      title: '确定要删除记录？',
	      //content: '确定要删除记录？',
	      success: function (res) {
	          if (res.confirm) {
				  let key = _this.selectedIndexs[0]
				 if(_this.card_arr[key].syn_status==1){
					 _this.$Api.msg("已同步,无法删除",'error');
					 _this.$refs.table.clearSelection()
					 return
				 }
				 
				 // if(_this.card_arr[key].get_qty>0){ 
					//  if(_this.order_type == 0){
					// 	 //不能这么判断，收货也可以同时上架
					// 	 //_this.$Api.msg("该单据已有上架,请先删除上架记录");
					//  }else if(_this.order_type == 2){
					// 	 _this.$Api.msg("该单据已有出库,请先删除出库记录");
					// 	 _this.$refs.table.clearSelection()
					// 	 return
					//  }
				 // }
				 
				//删除本地记录、恢复源单正常状态
				if(_this.order_type == 0){
					//删除收货
					_this.$Db.dealProcureBillData(_this.card_arr[key].source_code,_this.card_arr[key].FBillNo,'-')
					.then(ress=>{
						_this.$refs.table.clearSelection()
						_this.$Api.msg('删除成功','error')
						
						setTimeout(()=>{
							_this.getlist()
						},1500)
						
					}).catch(err=>{
						_this.$Api.msg(err)
					}) 
				}else if(_this.order_type == 2){
					//删除拣货
					_this.$Db.dealAppmaterialBillData(_this.card_arr[key].source_code,_this.card_arr[key].FBillNo,'-')
					.then(ress=>{
						_this.$refs.table.clearSelection()
						_this.getlist()
					}).catch(err=>{
						_this.$Api.msg(err)
					}) 
				}
	          }
	      }
	  });
	},
	selectes(item) {
	  if (item == '') return
	  if(this.flag=='add'){
		  let emit_name = ''
		  //回调触发
		  if(this.order_type == 0){
			  emit_name = 'getShouhuo' //返回上架页
		  }else if(this.order_type == 2){
			  emit_name = 'getPick' //返回出库页
		  }
		  
		  uni.navigateBack({
		    delta: 1,
		    success: () => {
		      uni.$emit(emit_name, item)
		    }
		  });
	  }else{
		  uni.navigateTo({
				url:'/pages/stockbill/item?FBillNo='+item.FBillNo+'&order_type='+item.order_type,
				delta:1
		  })
	  }
	},
	toDetail(item){
		/* 
		//到列表页
		uni.navigateTo({
			url:'/pages/stockbill/list?FBillNoPda='+item.FBillNo+'&order_type=1',
			delta:1
		}) */
		//直接到明细页
		uni.navigateTo({
			url:'/pages/stockbill/item?FBillNo='+item.FBillNo+'&order_type='+item.order_type,
			delta:1
		})
	},
	toSyn(){
		//回传数据
		let _this = this;
		if(!this.selectedIndexs.length||this.selectedIndexs.length>1){
			this.$Api.msg("请选择单条记录进行同步");
			return 
		}
		let bill = this.card_arr[this.selectedIndexs[0]]
		if(bill.syn_status){
			this.$Api.msg("该记录已同步,请勿重复操作");
			return
		}
		
		uni.showModal({
		    title: '确定要同步记录？',
		    //content: '确定要删除记录？',
		    success: function (res) {
		        if (res.confirm) {
					_this.$Db.backSynData('stockbill',bill,bill.order_type).then(res=>{
						_this.$Api.msg('同步成功','success')
						setTimeout(()=>{
							_this.getlist()
						},1000)
					}).catch(err=>{
						_this.$Api.msg(err)
					})
				}
			},
		})
	},
	toUnSyn(){
		//撤销同步，针对同步失败的单据
		let _this = this;
		if(!this.selectedIndexs.length||this.selectedIndexs.length>1){
			this.$Api.msg("请选择单条记录进行撤销");
			return 
		}
		let bill = this.card_arr[this.selectedIndexs[0]]
		if(!bill.syn_status){
			this.$Api.msg("该记录未同步,无法撤销");
			return
		}
		uni.showModal({
		    title: '确定要撤销同步记录？',
		    content: '撤销同步记录并删除操作记录',
		    success: function (res) {
		        if (res.confirm) {
					_this.$Db.unSynData('stockbill',bill.FBillNo).then(res=>{
						_this.$Db.deleteTableData('stockbill','FBillNo',bill.FBillNo)
						_this.$Db.deleteTableData('stockbillentry','FBillNo',bill.FBillNo)
						_this.$Api.msg('撤销成功','success')
						setTimeout(()=>{
							_this.getlist()
						},1000)
					}).catch(err=>{
						_this.$Api.msg(err)
					})
				}
			},
		})
	},
	synPdaorder(order_type){
		//下载盘点任务，json文件
		let _this = this
		uni.showModal({
			title: '温馨提醒',
			content: '确定要下载WMS平台拣货单？',
			success: function (res) {
				if (res.confirm) {
					uni.showLoading({
						mask:true
					});
					_this.$Api.synPdaorder(order_type).then(res => {
						if(res.data.code == 1){
							_this.$Db.synPickShouhuoOrder(res.data.data).then(res=>{
								_this.getlist()
							}).catch(err=>{
								_this.$Db.addLog('下载pda单据异常1',err)
							});
							uin.hideLoading() 
						}else{
							_this.$Api.msg('下载失败或暂无单据')
							_this.$Db.addLog('下载pda单据异常',res.data.msg)
							uin.hideLoading() 
						}
					})
				}
		}})
	}
  },
  onLoad(e) {
	this.flag = e.flag
	if(e.order_type!=undefined){
		this.order_type = e.order_type
		if(this.order_type == 2){
			this.right_options[0].text = '领料明细'
		}
	}
	this.getlist()
	this.$Func.setBarTitle(this.$Func.getOrderTypeName(this.order_type)+'记录')
  }
}
</script>
<style lang="less">
</style>